package org.ejc.struts.admin;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;
import org.ejc.api.executive.ConventionExecutiveAPIUtil;
import org.ejc.persist.model.Convention;
import org.ejc.persist.model.ConventionExecutive;
import org.ejc.session.EJCSession;

/**
 * @author Brian Boyle
 * @struts.action path="/struts/admin/createExecutiveAction" scope="request"
 *                parameter="methodToCall" name="createExecutiveForm"
 *                validate="false"
 *                input="/struts/admin/createExecutive.jsp"
 * 
 * @struts.action-forward name="preCreateExecSuccess" path="/struts/admin/createExecutive.jsp"
 * @struts.action-forward name="createExecSuccess" path="/struts/admin/editExecutive.jsp"
 * 
 */
public class CreateExecutiveAction extends DispatchAction {

	public final ActionForward preCreateExec(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception 
	{
		HttpSession session = request.getSession();
		EJCSession ejcSession = (EJCSession) session.getAttribute("ejcSession");
		ejcSession.setCurrentAction("Add Executive");
		return mapping.findForward("preCreateExecSuccess");
	}
	
	
	public final ActionForward createExec(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception 
	{
	
		ActionMessages errors = form.validate( mapping, request );
		if ( (errors != null && !errors.isEmpty())) {
			log.fatal("There are errors");
			saveErrors(request, errors);            
			//Setup the dropdown lists again
			return mapping.findForward("preCreateExecSuccess");
		}
		
		
		CreateExecutiveForm execForm=(CreateExecutiveForm)form;
		ConventionExecutive exec=execForm.copyToExecutive();
		HttpSession session = request.getSession();
		EJCSession ejcSession = (EJCSession) session.getAttribute("ejcSession");
		Convention con=new Convention();
		con.setConventionId(ejcSession.getConvention().getConventionId());
		exec.setConvention(con);
		
		
		
		
		Integer id=ConventionExecutiveAPIUtil.getLocalHome().create().createConventionExecutive(exec);
		execForm.setExecutiveId(id);
		
		ActionMessages messages = new ActionMessages();
		ActionMessage msg = new ActionMessage("info.register.createSuccessful");
		messages.add("message1", msg);
		saveMessages(request, messages);
		
		
		
		return mapping.findForward("createExecSuccess");
	}
	
}
